<template>
  <el-divider v-if="border" class="m-0"></el-divider>
  <el-footer class="flex items-center px-0 select-none">
    <el-pagination
      v-model:current-page="state.page"
      v-model:page-size="state.limit"
      :page-sizes="pageSizes"
      :disabled="disabled"
      :background="background"
      :class="`align-${align}`"
      small
      prev-text="上一页"
      next-text="下一页"
      layout="total,sizes,prev,pager,next,jumper"
      :total="total"
      @current-change="(v: number) => handlePaginationChange(v, state.limit)"
      @size-change="(v: number) => handlePaginationChange(state.page, v, true)"
    />
  </el-footer>
</template>

<script setup lang="ts">
import { omit } from 'lodash-es'

import { pageSizes } from '@/config'

interface IProps {
  total: number
  border?: boolean
  align?: 'right' | 'left' | 'between'
  disabled?: boolean
  background?: boolean
}
withDefaults(defineProps<IProps>(), {
  border: true,
  disabled: false,
  background: false, //todo 根据项目修改
  align: 'right',
  total: 0
})

interface IEmit {
  (event: 'change', pagination: { offset: number; limit: number }): void
}
const emit = defineEmits<IEmit>()

const state = reactive({
  page: 1,
  limit: 20,
  offset: 0
})

const handlePaginationChange = (
  page: number = state.page,
  limit: number = state.limit,
  resetPage: boolean = false
) => {
  state.page = resetPage ? 1 : page
  state.limit = limit
  state.offset = (page - 1) * limit
  emit('change', omit(state, 'page'))
}

defineExpose({
  reset() {
    state.page = 1
    state.limit = 20
    state.offset = 0
    handlePaginationChange()
  }
})
</script>

<style scoped lang="scss">
:deep(.el-pagination) {
  &[class*='align'] {
    @apply w-full;
  }

  &.align-between {
    .el-pagination__jump {
      // @apply ml-auto;
    }

    .btn-prev {
      @apply ml-auto;
    }
  }

  &.align-right {
    @apply ml-auto w-auto;
  }
}
</style>
